//
//  ViewController.m
//  DuDuCheckIn
//
//  Created by 蒋尚秀 on 2017/7/16.
//  Copyright © 2017年 -JSX-. All rights reserved.
//

#import "ViewController.h"
#import "JSXFMDB.h"
#import "Toast+UIView.h"
#import "QiniuSDK.h"
#import "QN_GTM_Base64.h"
#import <CommonCrypto/CommonHMAC.h>


#define Main_URL @"http://ocxnxj2p3.bkt.clouddn.com"
#define FILE_KEY @"DuDuCheck-ZhiHuiShu"
#define SCOPE @"coffeexiu:DuDuCheck-ZhiHuiShu"

@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    int todayCheck;
    NSInteger leftClassesCount;
}

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) NSString *scope;
@property (nonatomic, assign) NSInteger liveTime;
@property (nonatomic, strong) NSString *secretKey;
@property (nonatomic, strong) NSString *accessKey;

@property (nonatomic, strong) NSString *token;

@property (nonatomic, strong) UIView *patchSignInBackView;
@property (nonatomic, strong) UIView *patchSignInView;
@property (nonatomic, strong) UIDatePicker *datePicker;
@property (nonatomic, strong) UIButton *signInBtn;
@property (nonatomic, strong) UIButton *closeBtn;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [self createUI];
    
    [self downBtnClicked:nil];
}

-(void)reloadData
{
    _dataArray = [NSMutableArray arrayWithArray:[[JSXFMDB sharedJSXFMDB] selectAll]];
    todayCheck = [[JSXFMDB sharedJSXFMDB] selectTodayCheck];
    leftClassesCount = 91 - _dataArray.count;
    self.navigationItem.title = [NSString stringWithFormat:@"剩余 %ld 节课",leftClassesCount];
    [_tableView reloadData];
}

-(void)createUI
{
    self.navigationController.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 20, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-20)];;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    
    self.navigationItem.leftBarButtonItems = @[[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"up-2"] style:UIBarButtonItemStylePlain target:self action:@selector(uploadBtnClicked:)],
                                               [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"down-2"] style:UIBarButtonItemStylePlain target:self action:@selector(downBtnClicked:)]];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"补签到" style:UIBarButtonItemStylePlain target:self action:@selector(patchSignIn)];
    
    _patchSignInBackView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.view addSubview:_patchSignInBackView];
    _patchSignInView = [[UIView alloc] initWithFrame:CGRectMake(20, 100, [UIScreen mainScreen].bounds.size.width-40, [UIScreen mainScreen].bounds.size.height-200)];
    _datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(10, 10, _patchSignInView.frame.size.width-20, _patchSignInView.frame.size.height-150)];
    _patchSignInView.backgroundColor = [UIColor whiteColor];
    _patchSignInView.layer.shadowColor = [UIColor blackColor].CGColor;
    _patchSignInView.layer.shadowOffset = CGSizeMake(4, 4);
    _patchSignInView.layer.shadowOpacity = 0.6;//阴影透明度，默认0
    _patchSignInView.layer.shadowRadius = 4;//阴影半径，默认3
    _patchSignInView.layer.cornerRadius = 4;
    
    [_patchSignInView addSubview:_datePicker];
    
    _datePicker.datePickerMode = UIDatePickerModeDate;
    
    
    [_patchSignInBackView addSubview:_patchSignInView];
    _patchSignInBackView.hidden = YES;
    
    _closeBtn = [self createShadowButton:CGRectMake(30, CGRectGetMaxY(_datePicker.frame), (_datePicker.frame.size.width - 70)/2, 40) title:@"关闭" color:[UIColor darkGrayColor]];
    _signInBtn = [self createShadowButton:CGRectMake(CGRectGetMaxX(_closeBtn.frame) + 10, CGRectGetMaxY(_datePicker.frame), (_datePicker.frame.size.width - 70)/2, 40) title:@"签到" color:[UIColor redColor]];
    [_closeBtn addTarget:self action:@selector(closeBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [_signInBtn addTarget:self action:@selector(signInBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    
}

-(UIButton *)createShadowButton:(CGRect)frame title:(NSString *)title color:(UIColor *)color
{
    UIButton *button = [[UIButton alloc] initWithFrame:frame];
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:color forState:UIControlStateNormal];
    button.layer.borderColor = color.CGColor;
    button.layer.borderWidth = 2;
    button.layer.shadowColor = color.CGColor;
    button.layer.shadowOffset = CGSizeMake(2, 2);
    button.layer.shadowOpacity = 0.6;//阴影透明度，默认0
    button.layer.shadowRadius = 2;//阴影半径，默认3
    button.layer.cornerRadius = 2;
    
    [_patchSignInView addSubview:button];
    return button;
}

-(void)signInBtnClicked:(UIButton *)button
{
    NSDate *date = _datePicker.date;
    if([[JSXFMDB sharedJSXFMDB]insertCheck:date])
    {
        [self.view makeToast:@"签到成功" duration:2.0 position:@"center"];
        [self uploadBtnClicked:nil];
        [self reloadData];
    }
    else
    {
        [self.view makeToast:@"签到失败" duration:2.0 position:@"center"];
    }
}

-(void)closeBtnClicked:(UIButton *)button
{
    _patchSignInBackView.hidden = YES;
}

-(void)patchSignIn
{
    _patchSignInBackView.hidden = NO;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (todayCheck) {
        return _dataArray.count;
    }
    return _dataArray.count + 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    if (cell) {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.textAlignment = NSTextAlignmentCenter;
        if (indexPath.row==0) {
            
            cell.textLabel.textColor = [UIColor redColor];
        }
        else
        {
            cell.textLabel.textColor = [UIColor darkGrayColor];
        }
        
        if (todayCheck) {
            if (indexPath.row==0) {
                cell.textLabel.text = [NSString stringWithFormat:@"今日已签到 %@ %@", _dataArray[indexPath.row][@"date"], _dataArray[indexPath.row][@"week"]];
            }
            else
            {
                cell.textLabel.text = [NSString stringWithFormat:@"%@ %@", _dataArray[indexPath.row][@"date"], _dataArray[indexPath.row][@"week"]];
            }
        }
        else if(indexPath.row!=0)
        {
            cell.textLabel.text = [NSString stringWithFormat:@"%@ %@", _dataArray[indexPath.row-1][@"date"], _dataArray[indexPath.row-1][@"week"]];
        }
        else if(indexPath.row==0)
        {
            cell.textLabel.text = @"签到上课";
        }

    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        if (!todayCheck) {
            [[JSXFMDB sharedJSXFMDB] insertCheck:[NSDate date]];
            todayCheck = 1;
        }
        else
        {
            [[JSXFMDB sharedJSXFMDB] deleteCheck:[NSDate date]];
            todayCheck = 0;
        }
        [self uploadBtnClicked:nil];
        [self reloadData];
    }
}


- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row==0) {
        return NO;
    }
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row==0) {
        return;
    }
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        NSInteger row = todayCheck?indexPath.row:indexPath.row-1;
        if([[JSXFMDB sharedJSXFMDB] deleteCheckWith:_dataArray[row][@"date"]])
        {
            [_dataArray removeObjectAtIndex:row];
            [_tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
            [self.view makeToast:@"删除成功" duration:2.0 position:@"center"];
            
            [self uploadBtnClicked:nil];
        }
        // Delete the row from the data source.
        
        
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
}

-(void)uploadBtnClicked:(UIButton *)sender
{
    NSString * path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:@"CheckDB.db"];
    [self uploadFileToQNFilePath:path];
}

-(void)downBtnClicked:(UIButton *)sender
{
    double radom = [[NSDate date] timeIntervalSince1970];
    
    NSString *path = [[Main_URL stringByAppendingPathComponent:FILE_KEY] stringByAppendingString:[NSString stringWithFormat:@"?v=%f",radom]];
    
    NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:path] cachePolicy:1 timeoutInterval:15.0f];
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        NSLog(@"response = %@",response);
        
        [self.view makeToast:@"下载成功" duration:2.0 position:@"center"];
        NSString * path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:@"CheckDB.db"];
        BOOL res = [data writeToFile:path atomically:YES];
        if (res) {
            [self reloadData];
        }
        //得到了JSON文件 解析就好了。
        //        id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
        
        
        NSLog(@"%@", path);
        
    }];
}


- (void)uploadFileToQNFilePath:(NSString *)filePath {
    self.token = [self getToken];
    NSLog(@"%@",self.token);
    QNUploadManager *upManager = [[QNUploadManager alloc] init];
    QNUploadOption *uploadOption = [[QNUploadOption alloc] initWithMime:nil progressHandler:^(NSString *key, float percent) {
        NSLog(@"percent == %.2f", percent);
    }
                                                                 params:nil
                                                               checkCrc:NO
                                                     cancellationSignal:nil];
    [upManager putFile:filePath key:FILE_KEY token:self.token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        [self.view makeToast:@"上传成功" duration:2.0 position:@"center"];
        [[NSUserDefaults standardUserDefaults] setObject:resp[@"key"] forKey:@"MyAccount"];
        NSLog(@"info ===== %@", info);
        NSLog(@"resp ===== %@", resp);
    }
                option:uploadOption];
}

#pragma mark -QiNiu

-(NSString *)getToken
{
    self.scope = SCOPE;
    self.liveTime = 99999999;
    self.secretKey = @"3j-f9I8cxIAVfj2SyT_g1zYh4F2rYlhh2nyBCCpQ";
    self.accessKey = @"osRv7vwpfsojgs7dPB3GqWwCtmO2PBWnYzXHEpd9";
    NSMutableDictionary *authInfo = [NSMutableDictionary dictionary];
    [authInfo setObject:self.scope forKey:@"scope"];
    //    [authInfo setObject:self.scope forKey:@"saveKey"];
    //    [authInfo setObject:@"0" forKey:@"insertOnly"];
    [authInfo setObject:[NSNumber numberWithLong:[[NSDate date] timeIntervalSince1970] + self.liveTime * 24 * 3600]
                 forKey:@"deadline"];
    
    NSData *jsonData =
    [NSJSONSerialization dataWithJSONObject:authInfo options:NSJSONWritingPrettyPrinted error:nil];
    NSString *encodedString = [self urlSafeBase64Encode:jsonData];
    
    NSString *encodedSignedString = [self HMACSHA1:self.secretKey text:encodedString];
    
    NSString *token =
    [NSString stringWithFormat:@"%@:%@:%@", self.accessKey, encodedSignedString, encodedString];
    
    return token;
}

- (NSString *)urlSafeBase64Encode:(NSData *)text {
    NSString *base64 =
    [[NSString alloc] initWithData:[QN_GTM_Base64 encodeData:text] encoding:NSUTF8StringEncoding];
    base64 = [base64 stringByReplacingOccurrencesOfString:@"+" withString:@"-"];
    base64 = [base64 stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
    return base64;
}

- (NSString *)HMACSHA1:(NSString *)key text:(NSString *)text {
    const char *cKey = [key cStringUsingEncoding:NSUTF8StringEncoding];
    const char *cData = [text cStringUsingEncoding:NSUTF8StringEncoding];
    
    char cHMAC[CC_SHA1_DIGEST_LENGTH];
    
    CCHmac(kCCHmacAlgSHA1, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
    
    NSData *HMAC = [[NSData alloc] initWithBytes:cHMAC length:CC_SHA1_DIGEST_LENGTH];
    NSString *hash = [self urlSafeBase64Encode:HMAC];
    return hash;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
